Ext.define('AgenteNET.controller.Autenticacao', {
	extend : 'Ext.app.Controller',
	tempoConexao:600000,

	views : [ 'Login' ],

	init : function() {
		this.control({
			'#Login field' : {
				specialkey : function(field, event) {
					if (event.getKey() == Ext.EventObject.ENTER) {
						var win = field.up('window');
						var submit = win.down('button[type="submit"]');
						if (submit)
							submit.fireEvent('click', submit, event);
					}
				}
			},
			'#Login' : {
				show : function(win) {
					var form = win.down('form');
					form.down('textfield[name="password"]').setValue();
					form.down('textfield[name="login"]').focus(true, 1000);
				}
			},
		});
	},

	login : function() {
		this.getView('Login').create();
	},
	autenticar : function(btn) {
		Ext.util.Cookies.clear('token');
		var form = btn.up('form').getForm();
		form.submit({
			scope : this,
			form : form,
			url : 'minhaconexao',
			chamadoPor : btn,
			success : function(form, op) {
				var expiry = new Date();
				expiry.setTime(expiry.getTime() + (this.tempoConexao * 1000));
				Ext.util.Cookies.set('token', op.result.data.token, expiry);
				this.application.getController('Conexao').monitorConexao();
				op.chamadoPor.up('window').close();
			},
			failure : function(form, op) {
				Ext.Msg.show({
					title : 'AUTENTICAÇÃO',
					msg : op.result.mensagem.msg,
					animateTarget : op.chamadoPor,
					icon : Ext.window.MessageBox.ERROR
				});
				op.chamadoPor.up('window').show();
			},
		});
	},
	desconectar:function(el){
		Ext.MessageBox.show({
			title : 'DESCONECTAR',
			msg : 'Confirma a desconexão do sistema?',
			animateTarget : el.getEl(),
			icon : Ext.MessageBox.QUESTION,
			buttons: Ext.MessageBox.YESNO,
            buttonText:{ 
                yes: "Sim", 
                no: "Não" 
            },
            scope:this,
            fn:function(resposta){
            	if(resposta=='yes'){
        			Ext.util.Cookies.clear('token');
        			this.application.getController('Conexao').monitorConexao();
            	}
            }
		});
	}

});
